﻿using System;
using System.Collections.Generic;
using System.Text;
using Boomerang.Common.Configuration;
using System.Threading;
using Boomerang.Common.Sms.BoomerangService;
using Boomerang.Common.Crm;
using System.Diagnostics;

namespace Boomerang.Service.Threading
{
    public class WorkerThreadReceive : WorkerThreadBase
    {
        public WorkerThreadReceive(Organization org, ManualResetEvent e, int index)
            : base(org, e, index) { }

        protected override void DoWork()
        {
            Trace.TraceInformation("Starting receiving work for Organization {0}", org);
            Response[] responses;
            //Retrieve new SMS from Boomerang
            try
            {

                responses = smsDataSource.GetAllNewResponses();
                if (responses == null)
                {
                    Trace.TraceInformation("No inbound messages for Organization {0}",org);
                    return;
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Cannot retrieve responses from Boomerang. {0} \n {1}", ex.Message, ex.StackTrace);
                return;
            }

            Trace.TraceInformation("Processing {0} inbound sms for Organization {1}", responses.Length, org);

            foreach (Response item in responses)
            {
                Trace.TraceInformation("Processing inbound sms id={0}", item.ResponseId);
                try
                {
                    CrmSms sms = new CrmSms(item);                    
                    sms.CrmSmsId = crmDataSource.Create(sms);
                    Trace.TraceInformation("Sms record created in CRM with guid={0}", sms.CrmSmsId);

                    // Modified by Taner
                    smsDataSource.SetResponseAsRead(item.ResponseId);
                    //smsDataSource.SetResponseAsRead(int.Parse(item.ResponseId));

                    Trace.TraceInformation("Sms id={0} marked as read in boomerang", sms.CrmSmsId);

                    //Get the parent and update it
                    if (!string.IsNullOrEmpty(item.OriginalMessageIdentifier))
                    {
                        Trace.TraceInformation("Inbound sms id={0} is a response updating in CRM the original Crm record {1}", item.ResponseId, item.OriginalMessageIdentifier);
                        crmDataSource.UpdateParentSms(new Guid(item.OriginalMessageIdentifier), sms);
                    }

                    Trace.TraceInformation("Finished processing inbound sms id={0}", item.ResponseId);
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Error at inbound sms id={0}. {1} \n {2}", item.ResponseId, ex.Message, ex.StackTrace);
                    continue;
                }
            }

        }
    }
}
